package 创建型设计模式.原型模式.demo;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 使用JSON序列化的方式进行深拷贝
 * 必须传入对象的class类型，否则无法反序列化
 * @Author lf
 * @Date 3/30/2024
 */
public class DeepCopyViaJsonWithTypeRef {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static <T> T deepCopy(T value,Class<T> clazz) {
        try {
            String json = objectMapper.writeValueAsString(value);
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
